"use client";
import NavBar from "./components/NavBar";
import Footer from "./components/Footer";
import VideoGrid from "./components/VideoGrid";
import SearchBar from "./components/SearchBar";
import { useState, useEffect } from "react";
import { VideoItem } from "./types/video";

export default function Home() {
  const [keyword, setKeyword] = useState("");
  const [category, setCategory] = useState<import("./types/video").VideoCategory | "全部" | undefined>("全部");
  const [videos, setVideos] = useState<VideoItem[]>([]);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(9);
  const [totalCount, setTotalCount] = useState(0);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    loadVideos(currentPage);
  }, [keyword, category, currentPage, pageSize]);

  const loadVideos = async (page: number) => {
    setLoading(true);
    try {
      let url = `/api/videos?size=${pageSize}&page=${page}`;
      
      if (keyword) {
        url = `/api/videos/search?keyword=${encodeURIComponent(keyword)}&limit=${pageSize}&offset=${(page - 1) * pageSize}`;
      } else if (category && category !== "全部") {
        url = `/api/videos/category?category=${encodeURIComponent(category)}&size=${pageSize}&page=${page}`;
      }
      
      const response = await fetch(url);
      const data = await response.json();
      
      if (data.success) {
        setVideos(data.data || []);
        setTotalCount(data.pagination?.total || data.data?.length || 0);
      }
    } catch (error) {
      console.error('加载视频失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const initDatabase = async () => {
    fetch("/api/db/init", {
      method: "POST",
    }).then(res => res.json()).then(data => {
      console.log("initDatabase", data);
    });
  };

  const handlePageChange = (page: number) => {
    setCurrentPage(page);
  };

  const totalPages = Math.ceil(totalCount / pageSize);

  const getPaginationItems = () => {
    const items = [];
    const maxVisiblePages = 5;
    let startPage = Math.max(1, currentPage - Math.floor(maxVisiblePages / 2));
    let endPage = Math.min(totalPages, startPage + maxVisiblePages - 1);
    
    if (endPage - startPage + 1 < maxVisiblePages) {
      startPage = Math.max(1, endPage - maxVisiblePages + 1);
    }

    if (startPage > 1) {
      items.push(
        <button key="first" onClick={() => handlePageChange(1)} className="px-3 py-1 rounded hover:bg-gray-100">1</button>
      );
      if (startPage > 2) {
        items.push(<span key="ellipsis-start" className="px-3">...</span>);
      }
    }

    for (let i = startPage; i <= endPage; i++) {
      items.push(
        <button
          key={i}
          onClick={() => handlePageChange(i)}
          className={`px-3 py-1 rounded ${currentPage === i ? 'bg-blue-500 text-white' : 'hover:bg-gray-100'}`}
        >
          {i}
        </button>
      );
    }

    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        items.push(<span key="ellipsis-end" className="px-3">...</span>);
      }
      items.push(
        <button key="last" onClick={() => handlePageChange(totalPages)} className="px-3 py-1 rounded hover:bg-gray-100">{totalPages}</button>
      );
    }

    return items;
  };

  return (
    <div className="min-h-screen">
      <NavBar />
      <main className="mx-auto w-full max-w-6xl px-4 py-6">
        <h1 className="mb-4 text-2xl font-semibold" onClick={initDatabase}>精选视频</h1>
        <SearchBar
          keyword={keyword}
          category={category}
          onChange={(n) => {
            setKeyword(n.keyword);
            setCategory(n.category);
          }}
        />
        {loading ? (
          <div className="py-10 text-center">加载中...</div>
        ) : (
          <>
            <VideoGrid videos={videos} refreshVideos={() => loadVideos(currentPage)} />
            {totalPages > 1 && (
              <div className="flex justify-center mt-8 space-x-1">
                <button 
                  onClick={() => handlePageChange(currentPage - 1)} 
                  disabled={currentPage === 1}
                  className="px-3 py-1 rounded hover:bg-gray-100 disabled:opacity-50"
                >
                  上一页
                </button>
                {getPaginationItems()}
                <button 
                  onClick={() => handlePageChange(currentPage + 1)} 
                  disabled={currentPage === totalPages}
                  className="px-3 py-1 rounded hover:bg-gray-100 disabled:opacity-50"
                >
                  下一页
                </button>
              </div>
            )}
          </>
        )}
      </main>
      <Footer />
    </div>
  );
}
